# -*- coding: utf-8 -*-
"""
.. todo:: initial pyknic doc

"""

# -----------------------------------------------------------------------------

# do this only in debug mode
if __debug__ and False:
    
    import logging
    
    log = logging.getLogger('pyknic._debug')

    from . import _settings
    
    # NOTE: not sure why all modules are already loadedd!?
    # keys = sys.modules.keys()
    # keys.sort()
    # for key in keys:
        # log.debug(str(key))
    
    # Replacement for __import__()
    def import_hook(name_, globals_=None, 
                            locals_=None, fromlist=None, level=-1):
        """
        Replaces the original __import__ method.
        
        .. todo:: only log newly loaded modules, but see
        .. note:: of above: all modules are already loaded!
            if not mod in sys.modules.values()

        """
        try:
            mod = _original_import(name_, globals_, locals_, fromlist, level)
            if not _settings.settings['documenting'] and \
                                        not _settings.settings['testing']:
                log.debug("loaded:" + str(mod))
            return mod
        except Exception as ex:
            if not _settings.settings['documenting'] and \
                                        not _settings.settings['testing']:
                log.error(str(ex))
            # need to raise it, the try ... except is only for logging
            raise ex

    # Replacement for reload()
    def reload_hook(module):
        """
        Replaces the original __reload__ method.
        """
        mod = _original_reload(module)
        log.debug("reloaded: "+ mod)
        return mod
        
    try:
        import __builtin__
    except ImportError as e:
        import builtins as __builtin__
    # Save the original hooks
    _original_import = __builtin__.__import__  # pylint: disable=C0103
    # Now install our hooks
    __builtin__.__import__ = import_hook

    
    _original_reload = __builtin__.reload      # pylint: disable=C0103
    __builtin__.reload = reload_hook
    

# -----------------------------------------------------------------------------
